//
//  LTOauthViewController.swift
//  微博08
//
//  Created by 123 on 16/3/3.
//  Copyright © 2016年 Tsr. All rights reserved.
//

import UIKit
import SVProgressHUD

class LTOauthViewController: UIViewController {
    
    // 加载loadView的时候讲view设置成webView
    override func loadView() {
        self.view = webView
        
        // 设置代理
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // 设置背景颜色
        view.backgroundColor = UIColor.whiteColor()
        
        // 设置导航栏
        setupNavigationBar()
        
        // 加载授权界面
        let request = NSURLRequest(URL: LTNetworkTools.sharedInstance.oauthLoginUrl())
        webView.loadRequest(request)
        
        
    }
    
    // 设置导航栏
    func setupNavigationBar() {
        // 设置左边Bar
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "oauthFill")
        
        // 设置右边Bar
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
    // MARK: item 的点击事件
    func oauthFill() {
        // 执行js代码,自动填充账号密码
        let js = "document.getElementById('userId').value='13006027522';document.getElementById('passwd').value='theman1314'"
        
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    func close() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // MARK: 懒加载
    lazy var webView: UIWebView = UIWebView()
}

extension LTOauthViewController: UIWebViewDelegate {
    // webView 开始加载请求
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showWithStatus("正在加载登录界面", maskType: SVProgressHUDMaskType.Black)
    }
    
    // 现在成功后隐藏界面
    func webViewDidFinishLoad(webView: UIWebView) {
        // 关闭
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
        if error?.code != 102 {
            SVProgressHUD.showErrorWithStatus("加载失败", maskType: SVProgressHUDMaskType.Black)
            
        }
    }
    
    // webView询问我们是否去加载某个请求, true去加载,false不加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        // absoluteString: 表示url的地址
        let urlString = request.URL?.absoluteString
        print("urlString: \(urlString)")
        
        // 点击 取消 按钮:http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        // 点击 授权 按钮:http://www.baidu.com/?code=2eeb03e83cf361aa0692aabcbb2bdcdf
        // 通过?后面是code=表示点击了授权按钮,不是code=开头,点击的是取消按钮
        
        // 1.判断是否是回调地址开头,是回调地址开头,表示用户点击了是授权或取消按钮
        if urlString!.hasPrefix(LTNetworkTools.sharedInstance.redirect_uri) {
            
            // 判断点击的是授权还是取消
            // 截取url地址?后面的请求参数
            // query:?后面的请求参数
            let query = request.URL?.query
            
            // 判断query是以code=开头表示点击的是 授=按钮, 其它的点击的是 取消 按钮
            let codeString = "code="
            if query!.hasPrefix(codeString) {
                // 2.授权按钮,截取code的值
                let queryNS = query! as NSString
                
                let code = queryNS.substringFromIndex(codeString.characters.count)
                
                // 3.1 调用CZUserAccountViewModel的方法去加载请求
                LTUserAccountViewModel.sharedInstance.loadAccessToken(code, accessTokenCallBack: { (error) -> () in
                    if error != nil {
                        print("获取accessToken出错: \(error)")
                        SVProgressHUD.showErrorWithStatus("网络不给力")
                        // 延迟操作
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                            // 账号保存成功
                            self.close()
                        })
                    }
                    
                })
                
            } else {
                // 取消按钮,关闭控制器
                close()
            }
            
            return false
            
        }else {
            // 2.不是授权回调地址,直接加载这个请求
            return true
        }
    }
}
